#!/bin/bash

# 音频收集系统服务器部署脚本

set -e

echo "🚀 开始部署音频收集系统到服务器..."

# 检查Docker和Docker Compose
echo "🔍 检查环境..."
if ! command -v docker &> /dev/null; then
    echo "❌ Docker未安装，请先安装Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose未安装，请先安装Docker Compose"
    exit 1
fi

echo "✅ Docker环境检查通过"

# 创建必要的目录
echo "📁 创建存储目录..."
mkdir -p storage/recordings
mkdir -p storage/static
chmod 755 storage/recordings
chmod 755 storage/static

echo "✅ 存储目录创建完成"
echo "   📁 recordings/ - 音频文件存储 (Docker数据卷)"
echo "   📁 static/ - 静态文件存储 (本地挂载)"

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down --remove-orphans

# 清理旧镜像 (可选)
read -p "是否清理旧的Docker镜像? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "🧹 清理旧镜像..."
    docker system prune -f
    docker image prune -f
fi

# 构建并启动服务
echo "🔨 构建并启动服务..."
docker-compose up -d --build

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "🔍 检查服务状态..."
docker-compose ps

# 检查应用健康状态
echo "🌐 检查应用健康状态..."
for i in {1..10}; do
    if curl -f http://localhost:5050/ &> /dev/null; then
        echo "✅ 应用启动成功！"
        break
    else
        echo "⏳ 等待应用启动... (尝试 $i/10)"
        sleep 5
    fi
done

# 显示部署信息
echo ""
echo "🎉 部署完成！"
echo "=" * 50
echo "📋 服务信息:"
echo "  🌐 应用地址: http://localhost:5050"
echo "  🌐 Nginx代理: http://localhost:80"
echo "  🗄️  MySQL端口: localhost:3307"
echo ""
echo "👤 管理员账号:"
echo "  用户名: admin"
echo "  密码: 123456"
echo ""
echo "📊 API接口:"
echo "  基础测试: http://localhost:5050/"
echo "  管理员登录: http://localhost:5050/api/admin/login"
echo "  用户注册: http://localhost:5050/api/auth/register"
echo ""
echo "🔧 管理命令:"
echo "  查看日志: docker-compose logs -f"
echo "  重启服务: docker-compose restart"
echo "  停止服务: docker-compose down"
echo "  进入容器: docker exec -it audio_collection_app bash"
echo ""
echo "📁 存储管理:"
echo "  查看录音: docker exec -it audio_collection_app ls -la /app/storage/recordings/"
echo "  查看数据卷: docker volume inspect audio-collection-backend_recordings_data"
echo "  备份录音: docker run --rm -v audio-collection-backend_recordings_data:/data -v \$(pwd):/backup alpine tar czf /backup/recordings_backup.tar.gz -C /data ."
echo ""
echo "⚠️  重要提醒:"
echo "  1. 请及时修改默认的管理员密码"
echo "  2. 请修改.env.production中的密钥"
echo "  3. 建议配置防火墙规则"
echo "  4. 定期备份数据库和录音文件"

# 显示容器状态
echo ""
echo "📊 容器状态:"
docker-compose ps
